package 动态线程池;


import java.util.concurrent.LinkedBlockingQueue;
class Worker extends Thread {
    //阻塞队列
    private LinkedBlockingQueue<Runnable> queue = null;
    //工作线程数
    private static int threadCount = 0;
    public Worker(LinkedBlockingQueue<Runnable> queue){
        super("worker");
        this.queue = queue;
    }

    public static int size() {
        return threadCount;
    }

    //重写run,从阻塞队列中取出任务，然后run
    public void run(){
        while(true){
            try {
                threadCount++;
                Runnable runnable = queue.take();
                runnable.run();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class MyThreadPool {
    //最大工作线程数默认为10
    private int maxThreadCount = 10;
    private LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
    //将任务加入线程池中
    public void submit(Runnable runnable) throws InterruptedException {
        //若当前线程数不足，就继续创建
        if(Worker.size() < maxThreadCount){
            Worker worker = new Worker(queue);
            worker.start();
        }
        //将任务放入
        queue.put(runnable);
    }
}
public class Test {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool pool = new MyThreadPool();
        pool.submit(new Runnable() {
            @Override
            public void run() {
                for(int i = 0; i < 100; i++){
                    int f = i;
                    System.out.println("当前第" + f +"个任务，执行线程：" + Thread.currentThread().getName());
                }
            }
        });
    }
}
